<template>
  <view class="login-container">
    <!-- 背景装饰元素 -->
    <view class="decor-circle circle-1"></view>
    <view class="decor-circle circle-2"></view>

    <!-- 主要内容区 -->
    <view class="login-content">
      <!-- 头像占位 -->
      <view class="avatar-wrapper">
        <uni-icons type="contact-filled" size="100" color="#E0E0E0"></uni-icons>
      </view>

      <!-- 欢迎文案 -->
      <view class="welcome-text">欢迎使用智慧阅读</view>

      <!-- 登录按钮 -->
      <button class="login-btn" type="primary" :loading="isLogging" :disabled="isLogging" @click="handleLogin">
        {{ isLogging ? '登录中...' : '微信一键登录' }}
      </button>

      <!-- 底部提示 -->
      <view class="tip-text">登录后同步您的阅读记录和书架</view>
    </view>

    <!-- 底部装饰 -->
    <view class="bottom-decor"></view>
  </view>
</template>

<script>
  import {
    mapMutations
  } from 'vuex'

  export default {
    name: "my-login",
    data() {
      return {
        isLogging: false, // 登录状态标识
        userInfo: {},
        token: ''
      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken']),
      ...mapMutations('m_book', ['updateBookList']),

      async handleLogin() {
        if (this.isLogging) return

        this.isLogging = true

        try {
          // 获取用户信息
          const userInfoRes = await this.getUserProfile()
          this.userInfo = userInfoRes.userInfo

          // 获取登录凭证
          const loginRes = await this.getLoginCode()
          if (!loginRes.code) throw new Error('获取登录凭证失败')

          // 发送登录请求
          const loginData = await this.sendLoginRequest({
            nickname: this.userInfo.nickName,
            avatar: this.userInfo.avatarUrl,
            code: loginRes.code
          })

          this.token = loginData.token

          // 更新状态
          this.updateUserInfo(this.userInfo)
          this.updateToken(this.token)

          // 获取书架信息
          await this.getBookList()

          // 6. 根据登录状态跳转
          this.handleLoginSuccess(loginData.status)


        } catch (error) {
          console.error('登录失败:', error)
          uni.showToast({
            title: error.message || '登录失败，请重试',
            icon: 'none'
          })
        } finally {
          this.isLogging = false
        }
      },
      // 登录成功处理
      handleLoginSuccess(status) {
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        setTimeout(() => {
          if (status === 1) {
            // 新用户跳转完善信息
            uni.redirectTo({
              url: '/subpkg/profile/profile'
            })
          } else {
            // 老用户返回上一页
            uni.navigateBack()
          }
        }, 1500)
      },

      getUserProfile() {
        return new Promise((resolve, reject) => {
          uni.getUserProfile({
            desc: '获取用户信息',
            success: resolve,
            fail: (err) => reject(new Error('获取用户信息失败'))
          })
        })
      },

      getLoginCode() {
        return new Promise((resolve, reject) => {
          uni.login({
            success: resolve,
            fail: (err) => reject(new Error('获取登录凭证失败'))
          })
        })
      },

      async sendLoginRequest(data) {
        const {
          data: res
        } = await uni.$http.post('/user/login', data)
        if (res.code !== 1) throw new Error(res.message || '登录失败')
        return res.data
      },

      async getBookList() {
        const {
          data: res
        } = await uni.$http.get("/book/bookcase")
        if (res.code !== 1) throw new Error('获取书架失败')
        this.updateBookList(res.data)
      }
    }
  }
</script>

<style lang="scss">
  .login-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
    position: relative;
    overflow: hidden;

    .decor-circle {
      position: absolute;
      border-radius: 50%;
      background: rgba(192, 0, 0, 0.08);

      &.circle-1 {
        width: 400rpx;
        height: 400rpx;
        top: -100rpx;
        right: -100rpx;
      }

      &.circle-2 {
        width: 300rpx;
        height: 300rpx;
        bottom: 100rpx;
        left: -80rpx;
      }
    }

    .login-content {
      width: 80%;
      max-width: 500rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      z-index: 1;

      .avatar-wrapper {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 40rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      }

      .welcome-text {
        font-size: 36rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 60rpx;
      }

      .login-btn {
        width: 100%;
        height: 90rpx;
        line-height: 90rpx;
        border-radius: 45rpx;
        background-color: #C00000;
        color: #fff;
        font-size: 32rpx;
        margin-bottom: 30rpx;
        box-shadow: 0 4rpx 12rpx rgba(192, 0, 0, 0.3);

        &[disabled] {
          opacity: 0.7;
        }
      }

      .tip-text {
        font-size: 24rpx;
        color: #999;
      }
    }

    .bottom-decor {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 80rpx;
      background-color: #fff;
      border-top-left-radius: 40rpx;
      border-top-right-radius: 40rpx;
    }
  }
</style>
